//
//  AssMessageViewController.m
//  intelligent
//
//  Created by 甘世清 on 2024/2/7.
//

#import "AssMessageViewController.h"
#import "MessageLeftTableViewCell.h"
#import "MessageRifhtTableViewCell.h"
#import "MessageModel.h"
#import <SJVideoPlayer/SJVideoPlayer.h>
#import <QKeyboardEmotionView/QKeyboardEmotionView-umbrella.h>
#import <AVFoundation/AVFoundation.h>
#import "VipView.h"
#import "MeVipViewController.h"
#import <XYUUID/XYUUID.h>
@interface AssMessageViewController ()<QInputBarViewDelegate,QInputBarViewDataSource,InputBoardDataSource,InputBoardDelegate,UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,AVSpeechSynthesizerDelegate>
@property (nonatomic, assign) BOOL  isSend;
@property (nonatomic , strong)QInputBarView * putView;
@property (nonatomic , strong)QKeyboardManager * keyBoardManager;
@property (nonatomic , strong)SJVideoPlayer * player;
@property (nonatomic , strong) NSIndexPath * seletedIndexpath;
@property (nonatomic , strong) AVSpeechSynthesizer * synthesizer;


@end

@implementation AssMessageViewController

- (void)dealloc{
    DTLog(@"语音是否释放");
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.keyBoardManager.viewControllerWillDisappear = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 避免手势返回的时候输入框往下掉
    self.keyBoardManager.viewControllerWillDisappear = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.zx_navTitle = self.model.name;
    WS(weakSelf);
    [self zx_leftClickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
        [weakSelf.synthesizer stopSpeakingAtBoundary:AVSpeechBoundaryWord];
        [weakSelf SQ_popViewVC];
    }];
    
  
}

- (void)SQ_UIViewForSelfView{
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.zx_navBar.mas_bottom);
        make.bottom.equalTo(self.view).offset(-FootHeight-60);
    }];
    [self SQ_tableViewAddRefresh];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(scrollViewWillBeginDragging:)];
    [self.tableView addGestureRecognizer:tap];
    [self.keyBoardManager addBottomInputBarView:self.putView belowViewController:NO];
    [self.keyBoardManager bindTextView:self.putView.inputTextView];
    [self SQ_Header];
}

- (void)SQ_Header{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:@(self.page) forKey:@"current"];
    [dic setObject:@"30" forKey:@"size"];
    [dic setObject:self.model.roomId forKey:@"roomId"];
    [HttpTool post:@"chat/chatRecord" paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        NSDictionary * data = [[NSDictionary alloc]initWithDictionary:httpModel.data];
        NSArray * array = [MessageModel mj_objectArrayWithKeyValuesArray:[data objectForKey:@"records"]];
        [self.jsonArray addObjectsFromArray:[Manager sortArray:array increase:YES byKey:@"userid"]];
        if (array.count > 0) {
            if (self.page==1) {
                [self insertAndScrollToBottom:self.jsonArray.lastObject needClearInputText:YES];
            } else {
                [self.tableView reloadData];
            }
            self.page++;
        }
        [self.tableView.mj_header endRefreshing];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.message];
        [self.tableView.mj_header endRefreshing];
    }];
}
- (void)SQ_Foother{
    [self.tableView.mj_footer endRefreshing];
}
#pragma  mark UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.jsonArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WS(weakSelf);
    MessageModel * model = [self.jsonArray objectAtIndex:indexPath.item];
    NSString * Identifier = [NSString stringWithFormat:@"MessageLeftTableViewCell%ld",(long)indexPath.item];
    if (model.sendType) {
        MessageLeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
        if (!cell) {
            cell = [[MessageLeftTableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:Identifier];
        }
        model.portrait = @"智能 头像";
        cell.model = model;
        [cell.loveBtn setTouchBlock:^(SQCustomButton * _Nonnull button) {
            [weakSelf SQ_LoveBtnClick:model indexPath:indexPath];
        }];
        [cell setTypewriteEffectBlock:^{
            [weakSelf SQ_YuyinBtnClickindexPath:indexPath];
        }];
       
        [cell.fuzhiBtn setTouchBlock:^(SQCustomButton * _Nonnull button) {
            [weakSelf UIPasteboard:model];
        }];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {
        Identifier = [NSString stringWithFormat:@"MessageRifhtTableViewCell%ld",(long)indexPath.item];
        MessageRifhtTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
        if (!cell) {
            cell = [[MessageRifhtTableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:Identifier];
        }
        model.portrait = [UserModel share].portraitname;
        cell.model = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}


//cell点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.keyBoardManager hideAllBoardView];
}
 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageModel * model = [self.jsonArray objectAtIndex:indexPath.item];
    if (model.sendType) {
        return model.cellSize.height + 62+22+18;
    }
   return  [MessageRifhtTableViewCell FSCellHeightForTableView:tableView indexPath:indexPath cellContentViewWidth:0 bottomOffset:10];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    //用户手动拖动tableview，隐藏所有面板和键盘
    [self.keyBoardManager hideAllBoardView];
}
 
//添加到array中 + reload和滚到底部。 needClearInputText: 是否需要清空文本框输入的内容
- (void)insertAndScrollToBottom:(MessageModel *)contentModel needClearInputText:(BOOL)needClearInputText {
    if (contentModel ==nil) {
        return;
    }
    //添加到array中
    NSTimeInterval animationDuration = needClearInputText ? [self.putView clearInputTextBySend] : 0;
    //reloadData并滚到底部
    [self reloadDataAndScrollToBottomAnimated:YES animationDelay:animationDuration];
}
//reloadData并滚到底部
- (void)reloadDataAndScrollToBottomAnimated:(BOOL)animated animationDelay:(NSTimeInterval)animationDelay {
     BOOL resultAnimated = animated;
    if (animationDelay == 0){
        //如果textView的文本只有一行，那么清空输入框的时候，不会走onWholeInputViewHeightDidChange回调，也不会重新设置tableView的contentInset。所以就无需延时reloadData
        [self.tableView reloadData];
        [self scrollToBottomAnimated:resultAnimated];
    } else {
        //textView的文本大于一行，那么清空输入框的时候，会重设tableView的contentInset（并且我还是在0.2秒的动画里重设的），如果这时候reloadData，在低性能设备上会出现tableView来回上下移动的问题
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(animationDelay * NSEC_PER_SEC)), dispatch_get_main_queue(),  ^{
            [self.tableView reloadData];
            [self scrollToBottomAnimated:resultAnimated];
        });
    }
}
//滚到底部
-(void)scrollToBottomAnimated:(BOOL)animated {
    if (self.player.timeControlStatus == SJPlaybackTimeControlStatusPlaying) {
        MessageLeftTableViewCell * cell = [self.tableView cellForRowAtIndexPath:self.seletedIndexpath];
        [cell.lottieView play];
    }
    NSInteger rows = [self.tableView numberOfRowsInSection:0];
    if (rows > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:animated];
    }
}
#pragma mark - InputBoardDelegate
//整个“输入View”的高度发生变化（整个View包含bar和表情栏或者键盘，但是不包含底部安全区高度）
- (void)keyboardManager:(QKeyboardManager *)keyboardManager onWholeInputViewHeightDidChange:(CGFloat)wholeInputViewHeight reason:(WholeInputViewHeightDidChangeReason)reason {
    WS(weakSelf);
    BOOL alreadyAtBottom = [self SQ_alreadyAtBottom:weakSelf.tableView];
    UIEdgeInsets insets = UIEdgeInsetsZero;
    insets.top = 0;
    insets.bottom = wholeInputViewHeight - 60;
    //对应聊天界面，随着底部输入框的frame.y的变化，为了保持tableview一直都在输入条的上方，修改tableview的contentInset
    self.tableView.contentInset = insets;
    self.tableView.scrollIndicatorInsets = insets;
    if (reason == WholeInputViewHeightDidChangeReasonWillAddToSuperView) {
        //聊天界面，tableView要滚到底部
        dispatch_async(dispatch_get_main_queue(), ^{
        [self scrollToBottomAnimated:NO];
     });
        return;
    }
    if (reason == WholeInputViewHeightDidChangeReasonTextDidSend) {
        //是点击“发送”按钮清空输入框里的多行文字导致的输入栏高度变化
        return;
    }
    if (alreadyAtBottom) {
        //用自己的animations，问题就是会闪屏，尤其是tableview滚在上方时候 闪的越狠；好处是tableview在切换时候很跟手
        [UIView animateWithDuration:keyboardManager.inputBarHeightChangeAnimationDuration delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            [self scrollToBottomAnimated:NO];
        } completion:nil];
    } else {
        [self scrollToBottomAnimated:YES];
    }
}

#pragma mark - QInputBarViewDataSource
//@return 输入条上的UITextView，返回你自定义的UITextView
- (UITextView *)textViewForInputBarView:(QInputBarView *)inputBarView {
    FSTextView *tv = [[FSTextView alloc] init];
    tv.layer.cornerRadius = 4;
    tv.placeholder = @"这里输入你的问题...";
    return tv;
}
#pragma mark - QInputBarViewDelegate
// 输入框的高度发生了改变（因为输入框里的文字行数变化了），注意这里仅仅是TextView输入框的高度发生了变化的回调；becauseSendText：YES表示是因为调用了clearInputTextBySend去发送文本
- (void)inputBarView:(QInputBarView *)inputBarView inputTextView:(UITextView *)inputTextView heightDidChange:(CGFloat)changeValue becauseSendText:(BOOL)becauseSendText {
    //这里要告知Manager类
    [self.keyBoardManager inputTextViewHeightDidChange:becauseSendText];
}

//点击了“发送”按钮
- (void)onSendButtonSelect:(UIButton *)sender {
    //清空文本
    //发送给服务器
    [self inputBarView:self.putView onKeyboardSendClick:[self.putView textViewInputNormalText]];
}

-(BOOL)SQ_alreadyAtBottom:(UITableView*)view{
    if (((NSInteger)view.contentOffset.y) == ((NSInteger)view.contentSize.height + view.adjustedContentInset.bottom - CGRectGetHeight(view.bounds))) {
        return YES;
    }
    return NO;
}
//系统播放终止
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance{
    if (self.seletedIndexpath) {
        MessageLeftTableViewCell * cell1 = [self.tableView cellForRowAtIndexPath:self.seletedIndexpath];
        [cell1.lottieView stop];
    }
}

//点击了系统键盘的发送按钮
- (void)inputBarView:(QInputBarView *)inputBarView onKeyboardSendClick:(NSString *)inputNormalText {
   //发送消息
    if (![inputNormalText isNotEmpty]) {
        return;
    }
    if (self.isSend) {
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"助理当前正在全力思考中!")];
        return;
    }
    if (![UserModel share].isVip) {
        UserModel * mo = [UserModel share];
        if (mo.freeCount.integerValue == 0) {
            [self pushVIPAlert];
            return;
        }
        NSInteger count = mo.freeCount.integerValue - 1;
        if (count <=0) {
            count = 0;
        }
        mo.freeCount = [NSString stringWithFormat:@"%ld",count];
        [UserModel updateLocalUserModel:mo];
    }
    self.isSend = YES;
    UserModel * usermodel = [UserModel share];
    MessageModel * model  = [MessageModel new]; //创建我发的消息
    model.portrait =usermodel.portraitname;
    model.name = usermodel.name;
    model.content = inputNormalText;
    [self.jsonArray addObject:model];
    [self insertAndScrollToBottom:model needClearInputText:YES];
    MessageModel * model2  = [MessageModel new];//创建假的回复消息
    model2.name = self.model.name;
    model2.sendType = YES; //发送对象
    model2.type = 1; //类型为1
    [self.jsonArray addObject:model2];
    [self insertAndScrollToBottom:model2 needClearInputText:YES];
    WS(weakSelf);
   NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:inputNormalText forKey:@"content"];
    [dic setObject:self.model.roomId forKey:@"roomId"];
    [HttpTool post:@"chat/send" paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) { //成功了就删除假模型2 ,添加真模型3
        MessageModel * model3 = [MessageModel mj_objectWithKeyValues:httpModel.data];
        model3.typewriterType = 1;
        [weakSelf.jsonArray removeObject:model2];
        [weakSelf.jsonArray addObject:model3];
        weakSelf.isSend = NO;//允许再次提问
        [weakSelf.tableView reloadData];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        weakSelf.isSend = NO;
        [weakSelf.jsonArray removeObject:model]; //失败了删除添加的内容
        [weakSelf.jsonArray removeObject:model2];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf scrollToBottomAnimated:YES];
            inputBarView.inputTextView.text = inputNormalText;
            [YJProgressHUD showMsgWithoutView:httpModel.message];
        });
    }];
    self.putView.inputTextView.text = nil;
    //隐藏键盘
    [self.keyBoardManager hideAllBoardView];
}



-(void)UIPasteboard:(MessageModel*)model
{
    if (model.type ==1) {
        return;
    }
    UIPasteboard *pab = [UIPasteboard generalPasteboard];
      pab.string = model.content;
      if (pab == nil) {
          [YJProgressHUD showMessage:SQNSLocalString(@"复制失败")inView:self.tableView];
      } else {
          [YJProgressHUD showMessage:SQNSLocalString(@"复制成功")inView:self.tableView];
      }
}
-(void)SQ_LoveBtnClick:(MessageModel*)model indexPath:(NSIndexPath*)indexPath{
    if (model.type ==1) {
        return;
    }
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:model.userid forKey:@"id"];
    if (model.isCollect) {
        [dic setObject:@"0" forKey:@"type"];
    } else {
        [dic setObject:@"1" forKey:@"type"];
    }
    [HttpTool post:@"chat/collect" paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        model.isCollect = !model.isCollect;
        MessageLeftTableViewCell * cell1 = [self.tableView cellForRowAtIndexPath:indexPath];
        if (model.isCollect) {
             cell1.loveBtn.image = SQGetImage(@"收藏-亮");
            [YJProgressHUD showMessage:SQNSLocalString(@"收藏成功，个人中心收藏中查看") inView:self.tableView];
        } else {
            cell1.loveBtn.image = SQGetImage(@"收藏-灰");
        }
         
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.message];
    }];
}

-(void)SQ_YuyinBtnClickindexPath:(NSIndexPath*)indexPath {
    
    if (self.seletedIndexpath) {
        MessageLeftTableViewCell * cell1 = [self.tableView cellForRowAtIndexPath:self.seletedIndexpath];
        [cell1 SQ_UISetUp];
        [self.player stop];
        [self.synthesizer stopSpeakingAtBoundary:AVSpeechBoundaryWord];
        if (self.seletedIndexpath.item == indexPath.item) {
            self.seletedIndexpath = nil;
            return;
        }
    }
    MessageLeftTableViewCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
    dispatch_async(dispatch_get_main_queue(), ^{
          [cell.hud stopAnimating];
        cell.yuyinBtn.backgroundColor = UIColor.clearColor;
     });
    [cell.lottieView play];
    WS(weakSelf);
    if ([cell.model.url isNotEmpty]) {
        self.player.assetURL = [NSURL URLWithString:[cell.model.url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
        [self.player.playbackObserver setPlaybackDidFinishExeBlock:^(__kindof SJBaseVideoPlayer * _Nonnull player) {
            MessageLeftTableViewCell * cell = [weakSelf.tableView cellForRowAtIndexPath:weakSelf.seletedIndexpath];
            [cell.lottieView stop];
        }];
    } else {
         //本地播放
        AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:cell.model.content];
        utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
        [self.synthesizer speakUtterance:utterance];
    }
    self.seletedIndexpath = indexPath;
}
//vip弹窗
-(void)pushVIPAlert{
  [self.view endEditing:YES];
  if (![UserModel share].isVip) {
      VipView * view = [[VipView alloc]init];
      view.frame = CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT);
      LSTPopView * pop = [LSTPopView initWithCustomView:view
                                             parentView:nil
                                               popStyle:LSTPopStyleSmoothFromBottom dismissStyle:LSTDismissStyleSmoothToBottom];
      pop.hemStyle = LSTHemStyleCenter;
      [pop pop];
      LSTPopViewWK(pop)
      [pop setBgClickBlock:^{
          [wk_pop dismiss];
      }];
     
      [view setOpenVIPBlock:^{
          [wk_pop dismiss];
          MeVipViewController  * vc = [[MeVipViewController alloc]init];
          [[Manager SQ_getCurrentViewController].navigationController pushViewController:vc animated:YES];
      }];
      [view setCloseViewBlock:^{
          [wk_pop dismiss];
      }];
  }
}

- (QInputBarView *)putView{
    if (!_putView) {
        _putView = [[QInputBarView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-FootHeight-60, SCREEN_WIDETH, 60)];
        _putView.delegate = self;
        _putView.dataSource = self;
        QInputBarViewConfiguration *config = [QInputBarViewConfiguration defaultInputBarViewConfiguration];
        config.inputBarBackgroundColor = SQColor(@"#FFFFFF");
        config.inputBarBoardColor = UIColor.whiteColor;
        config.textViewBackgroundColor = SQColor(@"#EEEEEE");
        config.textColor = SQColor(@"#EEEEEE");
        config.voiceButtonHidden = YES;
        config.emotionButtonHidden = YES;
        config.extendButtonHidden = YES;
        UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 42, 42)];
        [btn addTarget:self action:@selector(onSendButtonSelect:) forControlEvents:UIControlEventTouchUpInside];
        [btn setImage:SQGetImage(@"发送-亮") forState:normal];
        config.rightSendButton = btn;
        [_putView setupWithConfiguration:config];
       
        _putView.inputTextView.textColor = SQColor(@"#333333");
    }
    return _putView;
}
- (QKeyboardManager *)keyBoardManager{
    if (!_keyBoardManager) {
        _keyBoardManager = [[QKeyboardManager alloc]initWithViewController:self];
        _keyBoardManager.dataSource = self;
        _keyBoardManager.delegate = self;
    }
    return _keyBoardManager;
}
 
- (SJVideoPlayer *)player{
    if (!_player) {
        _player = [SJVideoPlayer player];
//        _player.defaultEdgeControlLayer.hiddenBackButtonWhenOrientationIsPortrait = YES;
//        _player.automaticallyPerformRotationOrFitOnScreen = YES;
//        _player.defaultEdgeControlLayer.hiddenBottomProgressIndicator = NO;
////        _player.pauseWhenAppDidEnterBackground = NO;
////        _player.defaultEdgeControlLayer.onlyUsedFitOnScreen = NO;
//        _player.defaultEdgeControlLayer.automaticallyShowsPictureInPictureItem = NO;
////        _player.controlLayerAppearManager.interval = 5; // 设置控制层隐藏间隔
//        _player.resumePlaybackWhenAppDidEnterForeground = YES;//进入前台时, 是否恢复播放. 默认为 NO
    }
    return _player;
}
- (AVSpeechSynthesizer *)synthesizer{
    if (!_synthesizer) {
        _synthesizer = [[AVSpeechSynthesizer alloc] init];
        _synthesizer.delegate = self;
    }
    return _synthesizer;
}

@end
